<?php

namespace App\Http\Controllers\Admin;

use App\Model\Admin;
use App\Models\Node;
use App\Models\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class RoleController extends BaseController
{
    # 角色列表显示
    public function index()
    {
        $role_data = Role::orderBy("id","besc")->paginate($this->pagsize);
//        dump($role_data);die;
        $admin = new Admin();
        return view("admin.role.index",["role_data"=>$role_data,"admin"=>$admin]);
    }

    # 角色添加列表显示
    public function create()
    {
        return view("admin.role.create");
    }

    # 接收添加数据处理
    public function store(Request $request)
    {
        # 数据处理表单验证
        $data = $this->validate($request,[
            "name" => "required"
        ]);
        # 添加到数据库中
        Role::create($data);
        return redirect( route("admin.role.index"))->with("success","添加角色成功");
    }

    # 显示单条数据
    public function show(Role $role)
    {
        return 11;
    }

    # 显示编辑页面
    public function edit(Role $role)
    {
//        echo 11;die;
        $role_id = $role["id"];
        $list = Role::find($role_id);
        return view("admin.role.edit",compact("list"));
    }

    # 接收编辑的数据处理
    public function update(Request $request, Role $role)
    {
        # 表单验证
        $data = $this->validate($request,[
            "name" => "required",
        ]);
        $role_id = $role["id"];
        Role::where("id",$role_id)->update($data);
        return ["status"=>200,"msg"=>"修改角色成功","data"=>$data];
    }

    # 进行删除角色
    public function destroy(Role $role)
    {
        $role_id = $role["id"];
        Role::destroy($role_id);
        return ["status" => 200,"msg" => "删除成功"];
    }
    # 给用户配置权限
    public function auth(Request $request ,Role $role){
        if($request->isMethod("post")){
            $data =$request->get("auth_id");
            # 多对多同步数据
            $role->nodes()->sync($data);
            return redirect(route("admin.role.index"))->with("success","添加权限成功");
        }
        # 查询所有的数据权限
        $list = treeLevel(Node::get()->toArray());
        # 多对多关联数据查询，查询到当前所有的角色所有的权限
        $list_auth = $role->nodes()->pluck("id")->toArray();
        return view("admin.role.auth",compact("list","role","list_auth"));
    }
}
